<?php

class Userchat_model extends Base_Model
{
    Const TABLE = 'user_v2_chat';

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    /**
     * 聊天列表
     *
     * @param $where
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function getChatList($where, $page, $from, $to)
    {
    	//分页参数
    	$limit=$page*10;
    	$offset=0;
    	//初始化未读参数,$to为聊天对象id，$from为当前用户id
    	$this->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));
    	$cache_id = 'chat_'.$to."_".$from;
    	$unread=$this->cache->get($cache_id);
    	if(!empty($unread)){
    		$unread['total']=0;
    		$this->cache->save($cache_id, $unread, 86400*10);
    	}
    	
    	
        $data = $this->db->select('uc.message, uc.created, u.uid as id1, uv.uid as id2, uc.fromUser, u.userIcon as userIcon1, uv.userIcon as userIcon2')->from(self::TABLE.' as uc')
                    ->join('user_v2 as uv', 'uv.uid = uc.guiderId','LEFT')
                    ->join('user_v2 as u', 'u.uid = uc.uid', 'LEFT')
                    ->where($where)
                    ->where_in('uc.status',array(1,10))
                    ->order_by('uc.created','desc')
                    ->limit($limit, $offset)
                    ->get()
                    ->result_array();
        //将最新的聊天记录置于下方
        $data=array_reverse($data);
        //上次消息发送时间为初始基准
        $tflag=isset($unread['time'])?$unread['time']:time();
        if($data){
            foreach($data as &$v){
                if($v['fromUser']){
                    $v['userIcon'] = $this->img($v['userIcon1']);
                    $v['uid']=$v['id1'];
                }else{
                    $v['userIcon'] = $this->img($v['userIcon2']);
                    $v['uid']=$v['id2'];
                }
                
                //判断是否是当前用户发出的消息
                if($from==$v['uid']){
                	$v['isCurrentUser']=1;
                }else{
                	$v['isCurrentUser']=0;
                }
                
                $dif=abs(strtotime(date('Y-m-d',$v['created']))-strtotime(date('Y-m-d',$tflag)));
                //时间差为1天以上，显示日期
                if($dif>86339){
                	$v['sendtime']=date('Y年m月d日 H:i',$v['created']);
                }else{
                	$dif2=abs($v['created']-$tflag);
                	//时间差在一天以内，且超过2分钟的显示时间，没有的不显示
                	if($dif2>120){
                		$v['sendtime']=date('H:i',$v['created']);
                	}else{
                		$v['sendtime']='';
                	}
                }
                //重新确定时间差基准
                $tflag=$v['created'];
                
                unset($v['uid']);
                unset($v['id1']);
                unset($v['id2']);
                unset($v['created']);
                unset($v['userIcon1']);
                unset($v['userIcon2']);
                unset($v['fromUser']);
                
            }
        }

        return $data;
    }

    /**
     * 添加聊天消息
     * @param $data
     * @return int
     */
    public function addChat($data)
    {
        $this->db->insert(self::TABLE, $data);
        return $this->db->insert_id();
    }

    /**
     * 私信列表
     *
     * @param $uid
     * @param $type
     * @return mixed
     */
    public function getChatByUser($uid, $type, $page)
    {
    	//分页参数
    	$limit=$page*5;
    	$offset=0;
    	
    	$ret=array();
    	
    	if($type == 'GUIDER'){
            $sql = "
                    SELECT uid
                    FROM user_v2_chat
                    WHERE guiderId = ".$uid."
                    GROUP BY uid
                    ORDER BY created desc
                    LIMIT ".$offset.",".$limit;
            $query = $this->db->query($sql)->result_array();
            foreach($query as $v){
            	$data=$this->getChatInfoByuidAndguiderId($v['uid'], $uid, $type);
            	$data['userIcon']=$this->img($data['userIcon']);
            	$data['created']=date("Y.m.d H:i",$data['created']);
            	$data['unread']=$this->getUnread($v['uid'], $uid);
				$data['rev_id']=$v['uid'];
				$ret[]=$data;
            }
        
        }elseif($type == 'TOURIST'){
        	$sql = "
                    SELECT guiderId
                    FROM user_v2_chat
                    WHERE uid = ".$uid."
                    GROUP BY guiderId
                    ORDER BY created desc
                    LIMIT ".$offset.",".$limit;
        	$query = $this->db->query($sql)->result_array();
        	foreach($query as $v){
        		$data=$this->getChatInfoByuidAndguiderId($uid, $v['guiderId'], $type);
        		$data['userIcon']=$this->img($data['userIcon']);
        		$data['created']=date("Y.m.d H:i",$data['created']);
        		$data['unread']=$this->getUnread($v['guiderId'], $uid);
				$data['rev_id']=$v['guiderId'];
				$ret[]=$data;
        	}
        }
        
        return $ret;
    }
    /**
     * 获取聊天记录
     *
     * @param $uid
     * @param $guiderId
     * @param $type
     * @return mixed
     */
    public function getChatInfoByuidAndguiderId($uid,$guiderId,$type){
    	$sql="
    		  SELECT 
    			u.userIcon, u.userName, uc.created, uc.message
    		  FROM user_v2_chat as uc 
    		  LEFT JOIN user_v2 as u";
    	if($type=='GUIDER'){
    		$sql.=" ON u.uid=uc.uid";
    	}
    	else{
    		$sql.=" ON u.uid=uc.guiderId";
    	}
    			 
    	$sql.=" WHERE uc.guiderId=".$guiderId." AND uc.uid=".$uid;
    	$sql.=" ORDER BY created desc";
    	return $this->db->query($sql)->row_array(0);
    }
    /**
     * 留言对方不在线提醒
     */
    public function noticeOffline($touristid,$guiderid,$type){
    	
    }
    /**
     * 获取未读消息数目
     *
     * @param $from
     * @param $to
     * @return int
     */
    public function getUnread($from,$to){
    	$this->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));
    	$cache_id = 'chat_'.$from."_".$to;
    	$unread=$this->cache->get($cache_id);
    	if(!empty($unread)){
    		return $unread['total'];
    	}else{
    		return 0;
    	}
    	
    }
}
